//=============================================================================
// Scene_Shop.Window_ShopSell
//=============================================================================
const originItemListInit = Window_ShopSell.prototype.initialize;
Window_ShopSell.prototype.initialize = function (x, y, width, height) {
    originItemListInit.call(this, x, y, width, height);
    this._backgroundSprite = new Sprite();
    this._backgroundSprite.bitmap =
        ImageManager.loadBitmap('img/system/UI/', 'MenuBg_List');
    this.addChildAt(this._backgroundSprite, 0);
    this._backgroundSprite.x = -17;
    this._backgroundSprite.y = -1;
    this.createItemViewerWindow();
};


Window_ShopSell.prototype.createItemViewerWindow = function(){
  const [x, y, width, height] = [80, 100, 240, 334]
  this._viewerWindow = new Window_ItemViewer(x, y, width, height)
  this._viewerWindow.hide()

  const curScene = SceneManager._scene;
  curScene.addWindow(this._viewerWindow)
}

Window_ShopSell.prototype.showView = function(){
  if(!this._viewerWindow)return;
  const item = this.item()
  if(!item){
    // 老饕：无物品时隐藏
    this._viewerWindow.hide();
    return;
  }
  // 老饕：修改输入变量
  this._viewerWindow.showView(item);
}

Window_ShopSell.prototype.hideView = function(){
  if(!this._viewerWindow)return;
  this._viewerWindow.hide()
}

// changeWindowWidth
Window_ShopSell.prototype.windowWidth = function () {
    return 128;
};

Window_ShopSell.prototype.maxCols = function () {
  return 1;
};


// select
const originSelect = Window_ShopSell.prototype.select
Window_ShopSell.prototype.select = function (index) {
    originSelect.call(this, index)
    this.$emit('select', ...arguments)
}

// deselect
const originDeSelect = Window_ShopSell.prototype.deselect
Window_ShopSell.prototype.deselect = function () {
    originDeSelect.call(this)
    this.$emit('deselect', ...arguments)
}

const originRefresh = Window_ShopSell.prototype.refresh
Window_ShopSell.prototype.refresh = function() {
    originRefresh.call(this);
    this.showView();
    this.callUpdateHelp();
};


Window_ShopSell.prototype.drawIcon = function (iconIndex, x, y, alpha = 255) {
    const bitmap = ImageManager.loadSystem('IconSet');
    const pw = Window_Base._iconWidth;
    const ph = Window_Base._iconHeight;
    const sx = iconIndex % 16 * pw;
    const sy = Math.floor(iconIndex / 16) * ph;

    // 应用带透明度的icon
    const opacityBitmap = bitmap.clone(bit => bit.paintOpacity = alpha)
    this.contents.blt(opacityBitmap, sx, sy, pw, ph, x, y)
}

// 不可用项以红色显示（老饕：因此方法影响装备窗口绘制，故将可用条件判定方法修改为isEnabled，可通用）
Window_ShopSell.prototype.drawItemName = function (item, x, y, width) {
    width = width || 312
    if (item) {
        const iconBoxWidth = Window_Base._iconWidth + 4;
        this.resetTextColor();
        //if (!$gameParty.canUse(item)) {
        if (!this.isEnabled(item)){
            this.changeTextColor(this.hpGaugeColor1());
            this.drawIcon(item.iconIndex, x + 2, y + 2, 125);//alpha=125
        } else {
            this.drawIcon(item.iconIndex, x + 2, y + 2);
        }
        this.drawText(item.name.split("（")[0], x + iconBoxWidth, y, width - iconBoxWidth);
        this.drawItemLevel(item, x, y, width - iconBoxWidth);
    }
}

Window_ShopSell.prototype.isEnabled = function(item) {
  return item && (item.price > 0 || (item.itemCategory.contains('护驾') && item.price==0));
};

// 隐藏不可卖物品
Window_ShopSell.prototype.makeItemList = function() {
  this._data = $gameParty.allItems().filter(function(item) {
    if (DataManager.isItem(item)){
      if (item.id >= 61 && item.id <= 65)
        return false
    }
    // 排除物品里的可使用装备
    if (this._category !== 'equips'){
        if(CP.UseEquipManager.isEquipUsable(item))
          return false;
    }

    return this.includes(item) && ( (item.price > 0 || (item.itemCategory.contains('护驾') && item.price==0)));

  }, this);
  if (this.includes(null)) {
      this._data.push(null);
  }
  if (SceneManager._scene instanceof Scene_Item)
      this.listEquippedItems();


  // 物品排序
  this._data.sort(function (a, b) {
    if (!a || !b)
      return
    // 护驾按等级或种族排序
    if (a.itemCategory.contains('护驾') && a.itemCategory.contains('护驾')) {
      if (!a.enemyId || !b.enemyId)
        return
      if ($dataEnemies[a.enemyId] == undefined || $dataEnemies[b.enemyId] == undefined)
        return
      if (ConfigManager['enemySort']) {
        // 等级优先排序
        if (!$dataEnemies[a.enemyId].catchLevel || !$dataEnemies[b.enemyId].catchLevel)
          return
        if ($dataEnemies[b.enemyId].catchLevel - $dataEnemies[a.enemyId].catchLevel !== 0) {
          return $dataEnemies[b.enemyId].catchLevel - $dataEnemies[a.enemyId].catchLevel
        } else {
          if (!$dataEnemies[a.enemyId].classId || !$dataEnemies[b.enemyId].classId)
            return
          return $dataEnemies[a.enemyId].classId - $dataEnemies[b.enemyId].classId
        }
      } else {
        // 种族优先排序
        if (!$dataEnemies[a.enemyId].classId || !$dataEnemies[b.enemyId].classId)
          return
        if ($dataEnemies[a.enemyId].classId - $dataEnemies[b.enemyId].classId !== 0) {
          return $dataEnemies[a.enemyId].classId - $dataEnemies[b.enemyId].classId

        } else {
          if (!$dataEnemies[a.enemyId].catchLevel || !$dataEnemies[b.enemyId].catchLevel)
            return
          return $dataEnemies[b.enemyId].catchLevel - $dataEnemies[a.enemyId].catchLevel
        }
      }
      // 非护驾则按图标编号排序
    } else {
      a = CP.UseEquipManager.getRealUseItem(a);
      b = CP.UseEquipManager.getRealUseItem(b);
      if (!a || !b)
        return
      return DataManager.itemSortMapping(a.iconIndex) - DataManager.itemSortMapping(b.iconIndex)
    }
  });
};



// 隐藏消耗值
Window_ShopSell.prototype.drawItemCost = function (item, wx, wy, width) {

};

//Yanfly.Item.Window_ItemList_drawItemNumber =
 //   Window_ItemList.prototype.drawItemNumber;
 /*
Window_ShopSell.prototype.drawItemNumber = function(item, dx, dy, dw) {
    if (DataManager.isIndependent(item)) {
      this.drawItemCarryNumber(item, dx, dy, dw);
      return;
    }
    Yanfly.Item.Window_ItemList_drawItemNumber.call(this, item, dx, dy, dw);
};

// 如有问题看看YEP_ItemCore.js里的Window_ItemList
Window_ShopSell.prototype.drawItemCarryNumber = function(item, dx, dy, dw) {
    if (DataManager.isItem(item)) {
      var index = $gameParty.items().indexOf(item);
    } else if (DataManager.isWeapon(item)) {
      var index = $gameParty.weapons().indexOf(item);
    } else if (DataManager.isArmor(item)) {
      var index = $gameParty.armors().indexOf(item);
    }
    if (index < 0) return this.drawEquippedActor(item, dx, dy, dw);
    index += 1;
    var max = $gameParty.getIndependentItemTypeMax(item);
    var fmt = Yanfly.Param.ItemCarryFmt;
    var text = fmt.format(Yanfly.Util.toGroup(index), Yanfly.Util.toGroup(max));
    if (Yanfly.Param.ItemQuantitySize) {
      this.contents.fontSize = Yanfly.Param.ItemQuantitySize;
    }
    if (index > max) {
      this.changeTextColor(this.powerDownColor());
    } else if (index === max) {
      this.changeTextColor(this.crisisColor());
    } else {
      this.changeTextColor(this.normalColor());
    }

    this.drawText(text, dx, dy, dw, 'right');
    this.resetFontSettings();
};
*/